package com.example.ch6_1resource;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private Button btnimg ,btnAsses;
    private ImageView ivimg , ivAsses;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnimg = findViewById(R.id.btn_img);
        ivimg = findViewById(R.id.img);
        btnAsses = findViewById(R.id.btn_xx);
        ivAsses = findViewById(R.id.img_xx);

        btnimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示目录中的图片
                showRawImg();
            }
        });

        btnAsses.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示assets目录中的图片
                showAeestsImg();
            }
        });




    }

    private void showAeestsImg() {

        try {
            //获取assetManager对象
            AssetManager am = getAssets();
            //获取图片对应输入流
            InputStream in = am.open("xx.jpg");
            //使用BitmapFactory将图片进行加工
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            //显示图片
            ivAsses.setImageBitmap(bitmap);


        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    private void showRawImg() {
        //得到resources对象
        Resources rs =  getResources();
        //获取raw目录中图片的输入流
        InputStream inImg = rs.openRawResource(R.raw.cat);
        //使用bitmapFactory 对象加载成bitmap对象
        Bitmap bitmap = BitmapFactory.decodeStream(inImg);

//        Bitmap bitmap1 = BitmapFactory.decodeResource(rs,R.raw.cat);

        //在图像控件中显示bitmap对象对应的图片
        ivimg.setImageBitmap(bitmap);



    }
}